package com.lzh.others.basejava.Exception_12;

import java.util.StringJoiner;

/**
 * @author by lzh
 * @Classname Rethrowing
 * @Description 12.6.2 重新抛出异常
 * printStackTrace() 显示的是原来异常抛出点的调用栈信息
 * 如果想在每个重新抛出点更新调用栈信息，可以调用 fillInStackTrace()方法，将返回一个Throwable对象，它会把
 * 当前调用栈信息写入原来那个异常对象
 * @Date 2022/6/29 22:39
 */
public class Rethrowing {
    public static void f() throws Exception {
        System.out.println("originating the exception in f()");
        throw new Exception("thrown from f()");
    }

    public static void g() throws Exception {
        try {
            f();
        } catch (Exception e) {
            System.out.println("inside g(),e.printStackTrace()");
            e.printStackTrace(System.out);
            throw e;
        }
    }

    public static void h() throws Exception {
        try {
            f();
        } catch (Exception e) {
            System.out.println("Inside h(),e.printStackTrace()");
            e.printStackTrace(System.out);
            throw (Exception) e.fillInStackTrace();//更新异常栈信息
            //调用fillInStackTrace()的那一行就成为了异常的新发生地了
        }
    }

    public static void main(String[] args) {
        StringJoiner stringJoiner = new StringJoiner(",");
        System.out.println("stringJoiner = " + stringJoiner);
        try {
            g();
        } catch (Exception e) {
            System.out.println("main: printStackTrace()");
            e.printStackTrace(System.out);
        }
        try {
            h();
        } catch (Exception e) {
            System.out.println("main: printStackTrace()");
            e.printStackTrace(System.out);
        }
    }
}
